var TableEditable = function() {
	var validator;
	return {
		init : function() {
			var tableId = "pack_table";
			util.initCheckBox(tableId);
			//下拉框字典赋值
			util.getDictByParentKey("DCZTDM", 'pack_status', '全部');
			//电池使用情况赋值
			setPackUseStatusNum();
			function queryData(sSource, aoData, fnCallback) {
				aoData.push({
					"name" : "status",
					"value" : $("#pack_status").val()
				});
				$.ajax({
					"type" : "get",
					"contentType" : "application/json",
					"url" : sSource,
					"dataType" : "json",
					"data" : {
						"aoData" : JSON.stringify(aoData)
					},
					"success" : function(resp) {
						fnCallback(resp);
					}
				});
			};

			var t = $('#pack_table').DataTable({
				//'bStateSave':false,
				"processing" : true,
				"serverSide" : true,
				"autoWidth": false,
				"sAjaxSource" : "basic/packSerial/getPackSerial.mvc",
				"fnServerData" : queryData,
				"pageLength" : 10,
				"sDom" : "<'row-fluid'r>t<'row-fluid'<'span6'i><'span6'p>>",
				"oLanguage" :util.getDToLanguage(),
				"columns" : [ {
					"data" : "pkId",
					"render" : function(data, type, full, meta) {
						 return '<div class="checker" onclick="util.selectCheckBox(\'' + tableId + '\', this)"><span><input type="checkbox" class="checkboxes"/></span></div>';
					},
					"bSortable" : false
				},
				{
					"data" : "serialNo",
					"bSortable" : false
				}, 
				{
					"data" : "status",
					"bSortable" : false,
					"render" : function(data,type,full,meta) {
						if("已使用"==data){
							return "<span class=\"label label-success\">"+data+"</span>";
						}else if("报废"==data){
							return "<span class=\"label label-important\">"+data+"</span>";
						} else {
							return "<span class=\"label\">"+data+"</span>";
						}
					}
				} ],
				"fnDrawCallback" : function(oSetting) {
					util.clearSelected(tableId);
				}
			});
			
			//查询
			$("#btn_query").click(function() {
				var table = $('#pack_table').DataTable();
				table.draw(true);
			});
			//重置
			$("#btn_reset").click(function() {
		        $("#pack_search_form")[0].reset();
		    });
			//批量生成按钮点击
			$("#pack_table_add").click(function(){
				$("#greateID").modal({show:true,keyboard:false});
			});
			//批量生成按钮点击
			$("#pack_table_create").click(function(){
				$("#customID").modal({show:true,keyboard:false});
			});
			$("#btn_save").click(function(e) {
				e.preventDefault();
				var table = $('#pack_table').DataTable();   
				var _packCode = $("#pack_code").val().trim();
				if(_packCode == ''){
					rmsBox.notify('warning', {msg: '电池ID不能为空！',delay:3000});
					return false;
				} else {
					$.ajax({
						"type" : "post",
						"url" : "basic/packSerial/customID.mvc",
						"dataType" : "json",
						"async":false,
						"data" : {
							"packCode" : _packCode
						},
						"success" : function(resp) {
							if(resp.msg=='SUCCESS'){
								rmsBox.notify('success', {msg: '保存成功！'});
								$("#btn_close").click();           
								table.draw(true);  
							}else if(resp.msg == 'REPEAT'){
								rmsBox.notify('warning', {msg: '电池ID重复！',delay:3000});
							}else {
								rmsBox.notify('error', {msg: '出错了！',delay:3000});
							}
							
						}
					});
				}
			});

			$("#btn_close").on('click',function(){
				$("#pack_code").val("");
			})
			//删除----begin
			$("#pack_table_delete").on('click', function(){
				var d = [];
				d = util.getCheckedData("pack_table");
				if (d.length == 0) {
					util.showModal("#_alertModal", "请选择要操作的记录！");
				} else {
					//检查所选择数据状态
					var d = [];
					d = util.getCheckedData("pack_table");
					var idArray=[];
					for (var i=0;i<d.length;i++) {
						idArray.push(d[i].pkId);
					}
					$.ajax({
						"type" : "post",
						"url" : "basic/packSerial/checkPackStatus.mvc",
						"dataType" : "json",
						"async":false,
						"data" : {
							"pkId" : idArray.join(",")
						},
						"success" : function(resp) {
							if(resp==true){
								util.showModal("#_confirmModal", "您确定要删除选中的记录？", "_confirmModal_yes");
							}else{
								util.showModal("#_alertModal", "所选记录包含已使用或报废电池,请重新选择！");
							}
							
						}
					});
				}
			});
			$("#_confirmModal").on('click', '#_confirmModal_yes', function() {
				var d = [];
				d = util.getCheckedData("pack_table");
				var idArray=[];
				for (var i=0;i<d.length;i++) {
					idArray.push(d[i].pkId);
				}
				var table = $('#pack_table').DataTable();
				var selRows = table.rows('.selected');
				var selData = selRows.data();
				//var pkId = d[0].pkId;
				$.ajax({
					"type" : "post",
					"url" : "basic/packSerial/delete.mvc",
					"dataType" : "json",
					"async":false,
					"data" : {
						"pkId" : idArray.join(",")
					},
					"success" : function(resp) {
						if(resp.msg=='SUCCESS'){
							rmsBox.notify('success', {msg: '删除成功！'});
							selRows.remove();
							table.draw(true);
							setPackUseStatusNum();
						}else{
							rmsBox.notify('error', {msg: '删除失败！',delay:3000});
						}
						
					}
				});
			})
			//删除----end
			//
			$("#pack_table_import").on('click', function(e) {
				e.preventDefault();
				$("#add-file").modal({show:true,keyboard:false});
			});

			//上传文件
			$("#form_file_save").on('click', function(e) {
				e.preventDefault();
				var table = $("#pack_table").DataTable();
				$.ajaxFileUpload({
		            url: 'basic/packSerial/batchImportPackCode.mvc', 
		            type: 'post',
		            secureuri: false, //一般设置为false
		            fileElementId: 'uploadfile', // 上传文件的id、name属性名
		            dataType: 'json', //返回值类型，一般设置为json、application/json
		            success: function(data, status){ 
		            	if(data.msg=='SUCCESS'){
							rmsBox.notify('success', {msg: '保存成功！'});
							$("#form_btn_close").click();
							table.draw(true);
						}else{
							rmsBox.notify('error', {msg: '保存失败！',delay:3000});
						}
		            },
		            error: function(data, status, e){ 
		                console.log(e);
		            }
        		});
	        	
			});

			$("#form_file_download").on('click', function(e) {
				e.preventDefault();
				$.fileDownload('basic/packSerial/download.mvc', {
					httpMethod: 'POST',
					prepareCallback:function(url){
						
					},
					successCallback:function(url){
						//App.unblockUI($(loadingId));//停止loading
						//rmsBox.notify('success', {msg: '操作成功'});
					},
					failCallback: function (html, url) {
						//App.unblockUI($(loadingId));//停止loading
						rmsBox.notify('error', {msg: '下载失败！',delay:3000});
					}
				});
			});
			
			//生成----begin
			$(function(){
				
				$("#form_pack_save").click(function(){
					validator = validateMyForm("createID_form");
					if(validator.form()){
						save();
					}else{
						return false;
					}
				});
			})
			/*
			 * validate 自定义验证
			 */
			function validateMyForm(formId){
				return $( '#' + formId ).validate({  
					//onfocusout: false, 
				    //onkeyup: false,
					errorElement: 'em',
					errorClass: 'redStar',
					focusInvalid: false, 
					ignore: "",
			        rules:{  
			        	pack_num:{
			        		required: true,
			        		checkNum:true,
			        		range:[0,9999],
			        		remote: {  
			        		    url: "basic/packSerial/checkData.mvc",     //后台处理程序  
			        		    type: "post",    
			        		    async:false,//数据发送方式  
			        		    dataType: "json",           //接受数据格式     
			        		    data: {                     //要传递的数据  
			        		        packNum: function() {  
			        		            return $("#pack_num").val();  
			        		        }  
			        		    },
			        		    dataFilter: function (data) {　　　　//判断控制器返回的内容
		                            if (data == "true") {
		                                return true;
		                            }
		                            else {
		                                return false;
		                            }
		                        }
			        		}  
			        	}
			            },  
			        messages:{  
			        	pack_num:{
			        		required: '不能为空',
			        		remote:'数值过大',
			        		range:'数值过大'
			        	}
			            }, 
			            errorPlacement: function (error, element) { 
			            	//默认以span形式显示在输入框后
		                   error.insertAfter(element);
		                   $(element.next()).attr('title', $(error).text()).tooltip();
		                   $(error).text('');
		                }
			    }); 
			}
			$.validator.addMethod("checkNum",function(value,element,params){  
	            var checkNum = /^[0-9]*[1-9][0-9]*$/;  
	            return this.optional(element)||(checkNum.test(value));  
	        },"请输入正整数");
			/**
			 * 保存
			 */
			function save(){
				var table = $('#pack_table').DataTable();       
				var _packNum = $("#pack_num").val(); 
				App.blockUI($("#greateID"));//开始loading
				$.ajax({                                        
					"type" : "post",                            
					"url" : "basic/packSerial/createPack.mvc",  
					"dataType" : "json",  
					"async":false,
					"data" : {                                  
						"num" : _packNum                        
					},                                          
					"success" : function(resp) {
						App.unblockUI($("#greateID"));//停止loading
						if(resp.msg=='SUCCESS'){
							rmsBox.notify('success', {msg: '保存成功！'});
							$("#form_btn_close").click();           
							table.draw(true);                      
							setPackUseStatusNum();   
						}else{
							rmsBox.notify('error', {msg: '操作失败！',delay:3000});
						}
						               
					},
					"error":function (XMLHttpRequest, textStatus, errorThrown){
						App.unblockUI($("#greateID"));//停止loading
					 }
					})
			}
			$("#form_btn_close").on('click',function(){
				if (validator) {
					validator.resetForm();
				}
				$("#pack_num").val("");
			})
			//生成----end
			
			//电视使用情况查询
			function setPackUseStatusNum(){
				$.ajax({
					"type" : "post",
					"url" : "basic/packSerial/getPackUseStatus.mvc",
					"dataType" : "json",
					"async":false,
					"success" : function(resp) {
						$("#unUse_num").text(resp.unUse);
						$("#used_num").text(resp.used);
						$("#useless_num").text(resp.useless);
					}
				});
			}
		}
	};
}();





